package org.acghub.mtdb.common;

import org.acghub.mtdb.util.ElementHelper;
import org.w3c.dom.Element;

import java.util.Set;

/**
 * @author zhouhe
 */
public class Table extends Naming implements TypeDependency, Meta {

    private String key;
    private String value;
    private boolean autoIncrement;
    private Persistence persistence;
    private int cacheCapacity;
    private String lock;
    private String comment;
    private Type keyType;
    private Type valueType;

    public Table(Mtdb parent, Element self) throws Exception {
        super(parent, self);
    }

    @Override
    public void initialize(Element self) throws Exception {
        ElementHelper eh = new ElementHelper(self);
        Verify.verifyName(Verify.VerifyType.TABLE, getName());
        this.key = eh.getString("key");
        this.value = eh.getString("value");
        this.persistence = Persistence.of(eh.getString("persistence"));
        this.autoIncrement = eh.getBoolean("autoIncrement", false);
        this.lock = eh.getString("lock", getName());
        this.cacheCapacity = eh.getInt("cacheCapacity", 10240);
        this.comment = eh.getString("comment");
        eh.warnUnused("name");
    }

    @Override
    public boolean resolve() {
        if (!super.resolve()) {
            return false;
        }

        if ((keyType = TypeFactory.resolve(this, key, null, null)) == null) {
            return false;
        }
        if ((valueType = TypeFactory.resolve(this, value, null, null)) == null) {
            return false;
        }

        if (!keyType.supportTableKey()) {
            throw new RuntimeException("Key of table " + getName() + "don't support type:" + keyType.getName());
        }

        if (autoIncrement && !keyType.supportAutoIncrement()) {
            throw new RuntimeException("Key of table " + getName() + " not support autoIncrement");
        }

        if (!valueType.supportTableValue()) {
            throw new RuntimeException("Value of table " + getName() + "don't support type:" + valueType.getName());
        }
        return true;
    }

    @Override
    public void depends(Set<Type> types) {
        keyType.depends(types);
        valueType.depends(types);
    }

    public String getKey() {
        return key;
    }

    public String getValue() {
        return value;
    }

    public boolean isAutoIncrement() {
        return autoIncrement;
    }

    public Persistence getPersistence() {
        return persistence;
    }

    public int getCacheCapacity() {
        return cacheCapacity;
    }

    public String getLock() {
        return lock;
    }

    public String getComment() {
        return comment;
    }

    public Type getKeyType() {
        return keyType;
    }

    public Type getValueType() {
        return valueType;
    }
}
